<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/26 0026
 * Time: 17:31
 */
namespace app\manager\model;


use app\common\helper\ArrayHelper;
use app\common\helper\Obj2Array;
use app\common\model\Model;
use think\Session;

class MenuModel extends Model {
    const LEVEL_ONE = 1; // 菜单等级, 1级为顶级权限项可以拥有子级
    const LEVEL_TWO = 2; // 菜单等级，可以拥有子级
    const LEVEL_THREE = 3; // 菜单等级，没有子级

    const TYPE_PAGE = 2; // 页面菜单，带跳转的菜单
    const TYPE_MENU = 1; // 纯菜单，不带跳转的菜单

    public static function levelList() {
        return [
            self::LEVEL_ONE => '一级菜单',
            self::LEVEL_TWO => '二级菜单',
            //self::LEVEL_THREE => '三级菜单',// 这里是有三级菜单的，所有的实现都是实现了三级的，只是由于所选前端框架页面三级联动太麻烦了，舍弃掉
        ];
    }

    public static function typeList() {
        return [
            self::TYPE_MENU => '单纯菜单',
            self::TYPE_PAGE => '页面菜单',
        ];
    }

    public static function oneLevelList() {
        $model = new self();
        $list = $model->field(['id', 'title', 'p_id', 'level'])->where(['level' => self::LEVEL_ONE, 'status' => self::STATUS_OK])->select();
        if (!empty($list)) {
            $list = Obj2Array::resObject2Array($list);
        }
        return $list;
    }

    public static function twoLevelList() {
        $model = new self();
        $list = $model->field(['id', 'title', 'p_id'])->where(['level' => self::LEVEL_TWO, 'status' => self::STATUS_OK])->select();
        if (!empty($list)) {
            $list = Obj2Array::resObject2Array($list);
        }
        return $list;
    }

    public static function threeLevelList() {
        $model = new self();
        $list = $model->field(['id', 'title', 'route', 'p_id'])->where(['level' => self::LEVEL_THREE, 'status' => self::STATUS_OK])->select();
        if (!empty($list)) {
            $list = Obj2Array::resObject2Array($list);
        }
        return $list;
    }


    /**
     * 获取1、2父级菜单list以及1级菜单的子菜单加入数组
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function parent2LevelList() {
        $model = new self();
        $lists = $model->field('id, title, level, p_id')->where(['status' => self::STATUS_OK])->where('level', '<', 3)->select();

        if (!empty($lists)) {
            $lists = Obj2Array::resObject2Array($lists);
        }

        $lists = self::format2LevelList($lists);
        return $lists;
    }

    /**
     * 格式化数据
     *
     * @param $list
     * @return array
     */
    private static function format2LevelList($list) {
        $arr = [];
        $i = 0;
        //var_dump($list);
        foreach ($list as $li) {
            // 查找子级，并将其加入数组
            if ($li['level'] == self::LEVEL_ONE) {
                $arr[$i] = $li;
                $child = [];
                foreach ($list as $key => $v) {
                    if ($v['p_id'] == $li['id']) {
                        $child[] = $v;
                        unset($list[$key]);
                        //var_dump($list);die;
                    }
                }
                $arr[$i]['child'] = $child;
                $i++;
            }
        }
        //var_dump($arr);die;
        return $arr;
    }

    /**
     * 获取用户授权的菜单
     */
    public function menuList() {
        // role
        $sessionM = new Session();
        $manager = $sessionM->get('user');
        // 系统管理员，拥有所有菜单权限
        if ($manager['uid'] == 1) {
            return $this->getSystemMenu();
        }

        // 普通管理员的菜单权限处理
        $managerRoleM = new ManagerRoleModel();
        $role_ids = $managerRoleM->where(['manager_id' => $manager['uid']])->column('role_id');
        if (empty($role_ids)) {
            return [];
        }

        $menu = $this
            ->alias('m')
            ->field(['m.level', 'm.route', 'm.title', 'm.icon_class', 'm.id', 'm.p_id', 'm.type'])
            ->join('base_role_permission r', 'r.permission_id = m.id')
            ->where(['m.status' => MenuModel::STATUS_OK])
            ->where(['r.type' => RolePermissionModel::TYPE_MENU])
            ->where('r.role_id', 'IN',  $role_ids)
            ->order(['m.level'=> 'ASC', 'm.sort' =>  'ASC'])
            ->select();
        if (empty($menu)) {
            return [];
        }
        $menu = Obj2Array::resObject2Array($menu);
        //var_dump($menu);die;
        $list = [];
        foreach ($menu as $key => $m) {
            if ($m['level'] == self::LEVEL_ONE) {
                $list[$m['id']] = $m;
            } else if($m['level'] == self::LEVEL_TWO) {
                $list[$m['p_id']]['child'][$m['id']] = $m;
            } else if ($m['level'] === self::LEVEL_THREE) {
                $list[$this->findTopId($m['p_id'], $menu)]['child'][$m['p_id']]['child'][$m['id']] = $m;
            }
        }
        return $list;
    }


    // 获取系统管理员的菜单权限
    private function getSystemMenu() {
        $menu = $this
            ->field(['level', 'route', 'title', 'icon_class', 'id', 'p_id', 'type'])
            ->where(['status' => MenuModel::STATUS_OK])
            ->order(['level'=> 'ASC', 'sort' =>  'ASC'])
            ->select();
        if (empty($menu)) {
            return [];
        }
        $menu = Obj2Array::resObject2Array($menu);
        //var_dump($menu);die;
        $list = [];
        foreach ($menu as $key => $m) {
            if ($m['level'] == self::LEVEL_ONE) {
                $list[$m['id']] = $m;
            } else if($m['level'] == self::LEVEL_TWO) {
                $list[$m['p_id']]['child'][$m['id']] = $m;
            } else if ($m['level'] === self::LEVEL_THREE) {
                $list[$this->findTopId($m['p_id'], $menu)]['child'][$m['p_id']]['child'][$m['id']] = $m;
            }
        }
        return $list;
    }

    /**
     * 获取顶级菜单id
     *
     * @param $pid
     * @param $list
     * @return mixed
     */
    private function findTopId($pid, $list) {
        foreach ($list as $item) {
            if ($item['id'] == $pid) {
                return $item['p_id'];
            }
        }
    }
    
}